import pandas as pd
from dash import html, dash_table

from filter import data

df = pd.DataFrame(data)

test_cols = ['number', 'short_description', 't_scrq', 'state_id:name',
             'problem_id', 'problem_id:short_description',
             'fixed_by_chg_id:short_description']
df_test = df.loc[:, test_cols]
df_test.columns = ['失效编号', '失效标题', '生产日期', '状态',
                   '结论编号', '分析结论', '问题解决']
df_test['结论编号'].fillna('000000000000', inplace=True)
df_test['分析结论'].fillna('分析中', inplace=True)
df_test['生产月份'] = df_test['生产日期'].map(lambda x: str(x)[:7])

df_Mode = df_test.groupby(['结论编号', '分析结论'])['失效编号'].count().reset_index()
df_Mode.columns = ['id', 'mode', 'qty']
df_Mode.sort_values(by='qty', ascending=False, inplace=True)
df_Mode['cate'] = df_Mode['mode']


def data_bars(df, column):
    n_bins = 100
    bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
    ranges = [
        ((df[column].max() - df[column].min()) * i) + df[column].min()
        for i in bounds
    ]
    styles = []
    for i in range(1, len(bounds)):
        min_bound = ranges[i - 1]
        max_bound = ranges[i]
        max_bound_percentage = bounds[i] * 100
        styles.append({
            'if': {
                'filter_query': (
                        '{{{column}}} >= {min_bound}' +
                        (' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
                ).format(column=column, min_bound=min_bound, max_bound=max_bound),
                'column_id': column
            },
            'background': (
                """
                    linear-gradient(90deg,
                    rgba(255, 65, 54, 0.2) 0%,
                    rgba(255, 65, 54, 0.2) {max_bound_percentage}%,
                    white {max_bound_percentage}%,
                    white 100%)
                """.format(max_bound_percentage=max_bound_percentage)
            ),
            'paddingBottom': 2,
            'paddingTop': 2
        })

    return styles


mode_cate_columns = [
    {'name': "结论编号", 'id': "id", 'type': 'text', 'editable': False},
    {'name': "分析结论", 'id': "mode", 'type': 'text', 'editable': False},
    {'name': "失效数量", 'id': "qty", 'type': 'numeric', 'editable': False},
    {'name': "结论分类", 'id': "cate", 'type': 'text', 'presentation': 'input'},
]
tab2_mode_cate_table = dash_table.DataTable(
    id="mode_cate_table",
    data=df_Mode.to_dict('records'),
    columns=mode_cate_columns,
    hidden_columns=['id'],
    sort_action="native",
    filter_action="native",
    editable=True,
    style_data_conditional=[
        {
            'if': {
                'column_editable': False,  # True | False
            },
            'backgroundColor': 'rgb(245, 245, 245)',
            'border': '1px solid rgb(211, 211, 211)'
        },
        {
            'if': {
                'column_editable': False,  # True | False
                'state': 'active'
            },
            'backgroundColor': 'rgb(245, 245, 245)',
            'border': '1px solid rgb(211, 211, 211)'
        },
        {
            'if': {
                'column_id': 'qty',
            },
            'cursor': 'context-menu',
        },
        {
            'if': {
                'column_id': 'cate',
            },
            'backgroundColor': 'rgb(255, 255, 255)',
            'border': '1px solid rgb(211, 211, 211)',
            'cursor': 'text',
        },
        {
            'if': {
                'column_id': 'cate',
                'state': 'selected'  # 'active' | 'selected'
            },
            'backgroundColor': 'rgb(255, 255, 255)',
            'border': '2px solid rgb(21, 59, 99)',
            'cursor': 'text',
        },
        {
            'if': {
                'column_id': 'cate',
                'filter_query': '{cate} != {mode}'
            },
            'background_color': 'hotpink',
            'border': '2px solid rgb(21, 59, 99)',
            'cursor': 'text',
        },
        {
            'if': {
                'column_id': 'cate',
                'state': 'active',
                'filter_query': '{cate} != {mode}'
            },
            'background_color': 'hotpink',
            'border': '2px solid rgb(21, 59, 99)',
            'cursor': 'text',
        }
    ],
    style_table={'overflow': 'auto'},
    style_cell={'textAlign': 'left'},
)

cate_columns = [
    {'name': "结论分类", 'id': "cate", 'type': 'text', 'editable': False},
    {'name': "失效数量", 'id': "qty", 'type': 'numeric', 'editable': False},
]
tab2_cate_table = dash_table.DataTable(
    id="cate_table",
    columns=cate_columns,
    sort_action="native",
    editable=False,
    style_table={'overflow': 'auto'},
    style_cell={'textAlign': 'left'},
)

failure_table = dash_table.DataTable(
    id="failure_table",
    data=df_test.to_dict('records'),
    columns=[{'name': i, 'id': i} for i in df_test.columns],
    fixed_rows={'headers': True},
    sort_action="native",
    editable=False,
    style_table={'overflow': 'auto'},
    style_cell={'textAlign': 'left'},
)

tab3_output_table = dash_table.DataTable(
    id="output_table",
    editable=False,
    style_table={'overflow': 'auto'},
    style_cell={'textAlign': 'left'},
)


def discrete_background_color_bins(df, n_bins=5, columns='all'):
    import colorlover
    bounds = [i * (1.0 / n_bins) for i in range(n_bins + 1)]
    if columns == 'all':
        if 'id' in df:
            df_numeric_columns = df.select_dtypes('number').drop(['id'], axis=1)
        else:
            df_numeric_columns = df.select_dtypes('number')
    else:
        df_numeric_columns = df[columns]
    df_max = df_numeric_columns.max().max()
    df_min = df_numeric_columns.min().min()
    ranges = [
        ((df_max - df_min) * i) + df_min
        for i in bounds
    ]
    styles = []
    legend = []
    for i in range(1, len(bounds)):
        min_bound = ranges[i - 1]
        max_bound = ranges[i]
        backgroundColor = colorlover.scales[str(n_bins)]['seq']['Reds'][i - 1]
        color = 'white' if i > len(bounds) / 2. else 'inherit'

        for column in df_numeric_columns:
            styles.append({
                'if': {
                    'filter_query': (
                            '{{{column}}} >= {min_bound}' +
                            (' && {{{column}}} < {max_bound}' if (i < len(bounds) - 1) else '')
                    ).format(column=column, min_bound=min_bound, max_bound=max_bound),
                    'column_id': column
                },
                'backgroundColor': backgroundColor,
                'color': color
            })
        legend.append(
            html.Div(style={'display': 'inline-block', 'width': '60px'}, children=[
                html.Div(
                    style={
                        'backgroundColor': backgroundColor,
                        'borderLeft': '1px rgb(50, 50, 50) solid',
                        'height': '10px'
                    }
                ),
                html.Small(round(min_bound, 2), style={'paddingLeft': '2px'})
            ])
        )

    return (styles, html.Div(legend, style={'padding': '5px 0 5px 0'}))

#
# ModeList = []
# CategoryList = []
# CategoryCardList = []
# BadgeList = []
# for i, row in df_Mode.iterrows():
#     ModeList.append("_".join(['mode', row['no']]))
#     CategoryList.append("_".join(['cate', row['no']]))
#     BadgeList.append("_".join(['badge', row['no']]))
#     CategoryCardList.append(buildCategoryCard(row))
# print(ModeList)
# print(CategoryList)


# Mode_list = df_Mode.to_dict(orient='records')

# df_problem = df_test[['问题编号', '问题标题']].dropna().drop_duplicates()
# df_problem.columns = ['no', 'name']
# problem_list = df_problem.to_dict(orient='records')
#
# df_Mode_problem = df_test[['结论编号', '问题编号']].dropna().drop_duplicates()
# df_Mode_problem.columns = ['source', 'target']
# df_Mode_problem['no'] = df_Mode_problem.apply(lambda row: "-".join([row['source'], row['target']]), axis=1)
# Mode_problem_list = df_Mode_problem.to_dict(orient='records')
#
# def buildNode(nodeRecord, label):
#     data = {'group': 'nodes',
#             'data': {"id": nodeRecord['no'],
#                      "label": label,
#                      "name": nodeRecord['name']}}
#     return data
#
#
# def buildEdge(edgeRecord, label):
#     data = {'group': 'edges',
#             'data': {"id": edgeRecord['no'],
#                      "label": label,
#                      "source": edgeRecord['source'],
#                      "target": edgeRecord['target'],
#                      }}
#     return data
#
#
# problem_eles = [buildNode(i, "problem") for i in problem_list]
# Mode_eles = [buildNode(i, "Mode") for i in Mode_list]
# elements = problem_eles + Mode_eles
#
# Mode_problem_edges = [buildEdge(i, "fixed_by") for i in Mode_problem_list]
# edges = Mode_problem_edges
